const { request } = require('../../utils/request');
const pageBehavior = require('../../utils/pageBehavior');

const TYPE_OPTIONS = [
  { label: '全部事项', value: '' },
  { label: '报到流程', value: 'arrival' },
  { label: '宿舍入住', value: 'dorm' },
  { label: '国际学生', value: 'international' },
  { label: '资助与绿色通道', value: 'aid' },
  { label: '学业准备', value: 'academic' }
];

const TYPE_TAG_MAP = {
  arrival: 'info',
  dorm: 'neutral',
  international: 'warning',
  aid: 'success',
  academic: 'info'
};

const toDate = (value) => {
  if (!value) {
    return null;
  }
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return null;
  }
  return date;
};

const formatDateLabel = (value) => {
  const date = toDate(value);
  if (!date) {
    return value || '';
  }
  const month = `${date.getMonth() + 1}`.padStart(2, '0');
  const day = `${date.getDate()}`.padStart(2, '0');
  return `${month}/${day}`;
};

Page({
  behaviors: [pageBehavior],

  data: {
    items: [],
    types: TYPE_OPTIONS.map((item) => item.label),
    typeIndex: 0,
    currentTypeLabel: TYPE_OPTIONS[0].label
  },

  onLoad() {
    this.fetchData(TYPE_OPTIONS[0].value);
  },

  onShow() {
    this.updateTabBar(1);
  },

  async fetchData(type) {
    const query = type ? `?type=${encodeURIComponent(type)}` : '';
    const url = `/api/miniapp/milestones${query}`;

    await this.executeAsync(
      async () => {
        const res = await request({
          url,
          method: 'GET',
          showErrorToast: false
        });
        const raw = res?.data;
        const list = this.extractList(raw);
        const normalized = this.normalizeItems(list);
        
        if (normalized.length === 0) {
          this.setEmpty(true, '暂无事项');
        } else {
          this.setEmpty(false);
          this.setData({ items: normalized });
        }
      },
      {
        showLoading: true,
        showError: true,
        defaultMessage: '加载失败，请稍后再试'
      }
    );
  },

  extractList(raw) {
    if (Array.isArray(raw)) {
      return raw;
    }
    if (Array.isArray(raw?.records)) {
      return raw.records;
    }
    if (Array.isArray(raw?.list)) {
      return raw.list;
    }
    if (Array.isArray(raw?.data)) {
      return raw.data;
    }
    return [];
  },

  normalizeItems(list) {
    const sorted = list
      .map((item) => ({
        id: item.id || `${item.title}-${item.date}`,
        title: item.title || '未命名事项',
        description: item.description || item.content || '',
        type: item.type || '',
        typeLabel: item.typeLabel || item.category || '',
        date: item.date || item.planDate || item.time || '',
        startTime: item.startTime || '',
        status: item.status || ''
      }))
      .sort((a, b) => {
        const dateA = toDate(a.date) || toDate(a.startTime) || new Date();
        const dateB = toDate(b.date) || toDate(b.startTime) || new Date();
        return dateA.getTime() - dateB.getTime();
      });

    const today = new Date();
    let activeAssigned = false;
    return sorted.map((item) => {
      const eventDate = toDate(item.date) || toDate(item.startTime);
      let status = '';
      let active = false;
      if (eventDate) {
        if (eventDate.getTime() < today.getTime()) {
          status = 'completed';
        } else if (!activeAssigned) {
          active = true;
          activeAssigned = true;
        }
      }
      return {
        id: item.id,
        title: item.title,
        description: item.description,
        time: formatDateLabel(item.date || item.startTime),
        status,
        active,
        tagText: item.typeLabel || this.mapTypeLabel(item.type) || '其它',
        tagType: TYPE_TAG_MAP[item.type] || 'neutral'
      };
    });
  },

  mapTypeLabel(type) {
    const option = TYPE_OPTIONS.find((opt) => opt.value === type);
    return option ? option.label : '';
  },

  onTypeChange(event) {
    const index = Number(event.detail?.value || 0);
    const option = TYPE_OPTIONS[index] || TYPE_OPTIONS[0];
    this.setData({
      typeIndex: index,
      currentTypeLabel: option.label
    });
    this.fetchData(option.value);
  },

  reload() {
    this.clearError();
    const current = TYPE_OPTIONS[this.data.typeIndex] || TYPE_OPTIONS[0];
    this.fetchData(current.value);
  }
});
